import { http } from '@kit.NetworkKit'
import { Userinfo } from '../entrty/Userinfo'
import { PersistenceV2 } from '@kit.ArkUI'

let request = http.createHttp()
let userInfo:Userinfo = PersistenceV2.globalConnect({type: Userinfo, defaultCreator: () => new Userinfo()})

export function get<T>(url:string, params?:Object):Promise<T>{
  return new Promise<T>((resole, reject) => {
    if (params) {
      url += '?' + Object.keys(params).map((k) => `${k}=${params[k]}`).join('&')
    }
    let headers = {"Content-Type":"application/json"}
    if (userInfo.token) {
      headers['X-Hioshop-Token'] = userInfo.token
    }
    request.request(url,{
      method: http.RequestMethod.GET,
      header: headers
    })
      .then((res) => {
        if (res.responseCode == 200) {
          let t:T = JSON.parse(res.result as string)
          resole(t)
        }else {
          reject(new Error(`网络错误：${res.responseCode}`))
        }
      })
      .catch(e => reject(e))
  })
}

// export function get1<T>(url:string,data?:object):Promise<T>{
//   return new Promise<T>((resolve,reject) => { //异步
//     if (data) {
//       // url += '?' + Object.keys(data).map((k) => `${k} = ${data[k]}`).join('&')
//       url += '?'+ Object.keys(data).map((k) => `${k}=${data[k]}`).join('&')
//     }
//     request.request(url,{
//       // method:http.RequestMethod.GET //默认就是get，可写可不写
//     })
//       .then((response) => {
//         if (response.responseCode == 200) {
//           let res:Res<T> = JSON.parse(response.result.toString()) //解析，解析成为你指定的格式
//           if (res.code == 200) {
//             resolve(res.data)
//           } else {
//             reject(new Error(res.message))
//           }
//         } else {
//           reject(new Error(`网络错误${response.responseCode}`))
//         }
//       })
//       .catch((e:Error) => {
//         reject(e)
//       })
//   })
// }

export function post<T>(url:string,data:object):Promise<T>{
  return new Promise<T>((resolve,reject) => {
    let headers = {"Content-Type":"application/json"}
    if (userInfo.token) {
      headers['X-Hioshop-Token'] = userInfo.token
    }
    request.request(url,{
      method:http.RequestMethod.POST, //方法，请求方式为POST
      header:headers, //内容格式，当前格式为json(xml,protobuf,msgpack)
      extraData:data, //上传的数据
      readTimeout:5000, //读取超时时间
      connectTimeout:5000, //连接超时时间
    })
      .then((response) => {
        if (response.responseCode == 200) {
          let res:T = JSON.parse(response.result.toString()) //解析，解析成为你指定的格式
            resolve(res)
        } else {
          reject(new Error(`网络错误${response.responseCode}`))
        }
      })
      .catch((e:Error) => {
        reject(e)
      })
  })
}